<template>
  <div class="container">
    <div class="cards-row">
      <!-- 左侧分类树卡片 -->
      <a-card class="general-card">
        <template #title>分类树</template>
        <template #extra>
          <a-button type="primary" @click="openCreateModal()">
            <template #icon><icon-plus /></template>
            新增根分类
          </a-button>
        </template>
        
        <div class="search-wrapper">
          <a-input-search
            v-model="searchKeyword"
            placeholder="搜索分类名称或编码"
            button-text="搜索"
            search-button
            allow-clear
            @search="handleSearch"
          />
        </div>
        
        <a-spin :loading="loading" style="width: 100%">
          <div class="tree-container">
            <a-tree
              v-if="treeData.length"
              :data="treeData"
              :field-names="{ key: 'id', title: 'name' }"
              show-line
              block-node
              :selected-keys="selectedKeys"
              v-model:expanded-keys="expandedKeys"
              @select="handleSelectNode"
              :virtual-list-props="{ height: 600 }"
            >
              <template #title="node">
                <div class="tree-node-title">
                  <span>{{ node.name }}</span>
                </div>
              </template>
              <template #extra="node">
                <div class="node-actions">
                  <a-button type="text" size="mini" @click.stop="openEditModal(node)">
                    <template #icon><icon-edit /></template>
                  </a-button>
                  <a-button type="text" size="mini" @click.stop="openCreateModal(node.id)">
                    <template #icon><icon-plus /></template>
                  </a-button>
                  <a-button type="text" size="mini" status="danger" @click.stop="openDeleteConfirmModal(node.id)">
                    <template #icon><icon-delete /></template>
                  </a-button>
                </div>
              </template>
              <!-- 显式定义 switcher 图标 - 简化测试 -->
              <template #switcher-icon="{ node, expanded }">
                 <!-- 强制显示加号图标，忽略所有条件 -->
                 <icon-plus />
              </template>
            </a-tree>
          </div>
        </a-spin>
      </a-card>

      <!-- 右侧分类详情卡片 -->
      <a-card class="general-card detail-card">
        <template #title>
          <span class="card-title">
            <icon-info-circle style="margin-right: 8px;" />分类详情
          </span>
        </template>
        <template #extra>
          <a-space v-if="Object.keys(currentCategory).length > 0">
            <a-button type="outline" size="small" @click="openEditModal(currentCategory)">
              <template #icon><icon-edit /></template>
              编辑分类
            </a-button>
            <a-button type="primary" size="small" @click="openCreateModal(currentCategory.id)">
              <template #icon><icon-plus /></template>
              添加子分类
            </a-button>
          </a-space>
        </template>
        
        <div v-if="Object.keys(currentCategory).length > 0" class="detail-content">
          <div class="detail-header">
            <div class="category-name">{{ currentCategory.name }}</div>
            <a-tag :color="currentCategory.status !== 0 ? 'green' : 'red'" size="medium">
              {{ currentCategory.status !== 0 ? '启用' : '禁用' }}
            </a-tag>
          </div>
          
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">分类编码</div>
              <div class="info-value">{{ currentCategory.code || '无' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">排序</div>
              <div class="info-value">{{ currentCategory.sort || 0 }}</div>
            </div>
          </div>
          
          <div class="description-section">
            <div class="info-label">分类描述</div>
            <div class="description-content">
              {{ currentCategory.description || '暂无描述' }}
            </div>
          </div>
          
          <div class="detail-footer">
            <div class="related-info">
              <div class="info-label">关联信息</div>
              <div class="related-grid">
                <div class="related-item">
                  <icon-fire style="color: #ff7d00" />
                  <span>关联商品: 0</span>
                </div>
                <div class="related-item">
                  <icon-calendar style="color: #165DFF" />
                  <span>创建时间: {{ formatDate() }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="empty-detail">
          <a-empty description="请选择左侧分类查看详情">
            <template #image>
              <icon-folder style="font-size: 48px; color: var(--color-text-3);" />
            </template>
          </a-empty>
        </div>
      </a-card>
    </div>

    <!-- 新增/编辑分类弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalType === 'create' ? '新增分类' : '编辑分类'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :ok-loading="modalLoading"
      width="500px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
        auto-label-width
      >
        <!-- 仅在创建子分类时显示父级分类 -->
        <a-form-item field="parentId" label="父级分类" v-if="modalType === 'create' && form.parentId">
          <a-input v-model="form.parentName" placeholder="父级分类" readonly />
        </a-form-item>
        <a-form-item field="name" label="分类名称" required>
          <a-input v-model="form.name" placeholder="请输入分类名称" allow-clear @change="generateCode" />
        </a-form-item>
        <a-form-item field="code" label="分类编码" required>
          <a-input-group>
            <a-input v-model="form.code" placeholder="请输入分类编码" allow-clear style="width: calc(100% - 104px)" />
            <a-button @click="generateCode">自动生成</a-button>
          </a-input-group>
          <template #extra>
            <div class="code-tip">
              分类编码将用于系统内部关联和数据处理，建议使用英文、数字组合
            </div>
          </template>
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input-number v-model="form.sort" placeholder="数字越小越靠前" :min="0" :max="999" style="width: 100%;" />
        </a-form-item>
        <a-form-item field="status" label="状态" required>
          <a-radio-group v-model="form.status" type="button">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="description" label="分类描述">
          <a-textarea
            v-model="form.description" 
            placeholder="请输入分类描述"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除确认 Modal -->
    <a-modal
      v-model:visible="deleteModalVisible"
      title="确认删除"
      @ok="handleDeleteConfirm"
      @cancel="deleteModalVisible = false"
      ok-text="确定"
      cancel-text="取消"
      title-align="start"
      width="400px" 
    >
      <div>
        <p style="text-align: center;">确定要删除此分类及其所有子分类吗？此操作不可恢复。</p>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, h } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { 
  IconPlus, 
  IconEdit, 
  IconDelete, 
  IconSearch,
  IconFile,
  IconFolder,
  IconInfoCircle,
  IconMinus,
  IconFire,
  IconCalendar
} from '@arco-design/web-vue/es/icon';
import { useCargoCategoryStore } from '@/stores/cargo-category';

// 使用store
const cargoCategoryStore = useCargoCategoryStore();

// 数据加载和状态
const loading = ref(false);
const modalVisible = ref(false);
const modalLoading = ref(false);
const modalType = ref('create'); // create, edit
const searchKeyword = ref('');

// 分类树和选中状态
const treeData = ref([]);
const selectedKeys = ref([]);
const expandedKeys = ref([]);
const currentCategory = ref({});

// 表单引用和数据
const formRef = ref(null);
const form = reactive({
  id: undefined,
  parentId: undefined,
  parentName: '',
  name: '',
  code: '',
  sort: 0,
  status: 1,
  description: '',
  level: 1
});

// 重置表单函数
const resetForm = () => {
  form.id = undefined;
  form.parentId = undefined;
  form.parentName = '';
  form.name = '';
  form.code = '';
  form.sort = 0;
  form.status = 1;
  form.description = '';
  form.level = 1;
  formRef.value?.clearValidate(); // 清除校验状态
};

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称' },
    { maxLength: 30, message: '分类名称最多30个字符' }
  ],
  code: [
    { required: true, message: '请输入分类编码' },
    { match: /^[A-Za-z0-9-_]+$/, message: '分类编码只能包含字母、数字、下划线和连字符' }
  ],
  status: [
    { required: true, message: '请选择状态' }
  ]
};

// 控制删除确认 Modal
const deleteModalVisible = ref(false);
const categoryToDeleteId = ref(null);

// 计算当前最大层级
const maxExistingLevel = computed(() => {
  let maxLevel = 1;
  
  const findMaxLevel = (nodes, currentLevel) => {
    for (const node of nodes) {
      maxLevel = Math.max(maxLevel, currentLevel);
      if (node.children && node.children.length > 0) {
        findMaxLevel(node.children, currentLevel + 1);
      }
    }
  };
  
  findMaxLevel(treeData.value, 1);
  return maxLevel;
});

// 生命周期钩子
onMounted(() => {
  fetchCategoryList();
});

// 获取分类列表
const fetchCategoryList = async () => {
  loading.value = true;
  try {
    const result = await cargoCategoryStore.getCategoryList();
    if (result.success) {
      // 处理树形结构
      formatTreeData(result.data);
      if (selectedKeys.value.length === 0 && treeData.value.length > 0) {
        selectedKeys.value = [treeData.value[0].id];
      }
      Message.success('获取货物分类成功');
    } else {
      Message.error('获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    Message.error('获取分类列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  // TODO: 实现搜索功能
  if (searchKeyword.value) {
    Message.info(`搜索: ${searchKeyword.value}`);
  } else {
    fetchCategoryList();
  }
};

// 处理节点选择
const handleSelectNode = (keys, { node }) => {
  if (keys.length > 0) {
    selectedKeys.value = keys;
    // 查找并设置当前选中的节点数据
    const findNode = (nodes, key) => {
      for (const n of nodes) {
        if (n.id === key) return n;
        if (n.children) {
          const found = findNode(n.children, key);
          if (found) return found;
        }
      }
      return null;
    };
    currentCategory.value = findNode(treeData.value, keys[0]);
    if (currentCategory.value) {
      fetchCategoryDetail(currentCategory.value.id); // 获取并显示详情
    }
  } else {
    selectedKeys.value = [];
    currentCategory.value = {};
    fetchCategoryDetail(null); // 清空详情
  }
};

// 打开创建模态框
const openCreateModal = (parentKey = null) => {
  resetForm(); // 重置表单
  modalType.value = 'create';
  form.status = 1; // 默认启用
  form.sort = 0;   // 默认排序

  // 计算 Level
  if (!parentKey) { // 新增根分类
    form.parentId = 0; // 或 null，取决于后端
    form.parentName = '根分类';
    form.level = 1;
  } else { // 添加子分类
    if (!checkLevelLimit(parentKey)) return; // 检查层级限制
    
    form.parentId = parentKey;
    // 查找父节点信息
    const findNode = (nodes, key) => {
      for (const node of nodes) {
        if (node.id === key) return node;
        if (node.children) {
          const found = findNode(node.children, key);
          if (found) return found;
        }
      }
      return null;
    };
    const parentNode = findNode(treeData.value, parentKey);
    form.parentName = parentNode ? parentNode.name : '未知父分类';
    // 计算子分类的层级
    const findNodeLevel = (nodes, key, currentLevel = 1) => {
      for (const node of nodes) {
        if (node.id === key) return currentLevel;
        if (node.children) {
          const level = findNodeLevel(node.children, key, currentLevel + 1);
          if (level > 0) return level;
        }
      }
      return 0;
    };
    const parentLevel = findNodeLevel(treeData.value, parentKey);
    form.level = parentLevel > 0 ? parentLevel + 1 : 1; // 如果找不到父级，则有问题，默认为1
  }
  
  generateCode(); // 生成初始编码
  modalVisible.value = true;
};

// 打开编辑模态框
const openEditModal = (node) => {
  modalType.value = 'edit';
  
  // 填充表单
  form.id = node.id;
  form.name = node.name;
  form.code = node.code;
  form.sort = node.sort || 0;
  form.status = node.status !== undefined ? node.status : 1;
  form.description = node.description || '';
  
  modalVisible.value = true;
};

// 处理模态框确认
const handleModalOk = async () => {
  try {
    await formRef.value.validate();
    modalLoading.value = true;
    
    // 确保 parentId 存在于提交的数据中
    const data = { 
      name: form.name,
      code: form.code,
      parentId: form.parentId || 0, // 如果是根分类，parentId 传 0 或 null，取决于后端要求，这里用 0
      sort: form.sort,
      status: form.status,
      description: form.description,
      level: form.level // level 应该在 openCreateModal 时计算好并放入 form
    };
    if (modalType.value === 'edit') {
      data.id = form.id; // 编辑时需要 id
      // 编辑时 level 可以不传，让后端处理，或者从当前节点获取
      delete data.level; // 暂时不在编辑时传递 level
    }

    let result;
    if (modalType.value === 'create') {
      result = await cargoCategoryStore.createCategory(data);
    } else {
      result = await cargoCategoryStore.updateCategory(data.id, data);
    }
    
    if (result.success) {
      Message.success(modalType.value === 'create' ? '分类创建成功' : '分类更新成功');
      modalVisible.value = false;
      fetchCategoryList(); // 成功后刷新列表
    } else {
      // 显示后端返回的详细错误信息
      Message.error(result.message || (modalType.value === 'create' ? '分类创建失败' : '分类更新失败'));
    }
  } catch (error) {
    // 表单验证失败或其他前端错误
    if (error && error.message) {
      // 如果是后端返回的错误被包装了
      Message.error(error.message)
    } else {
      // 可能是表单验证未通过的错误对象
      console.error('保存分类时出错:', error);
      // 可以尝试显示一个通用错误，或者让校验信息显示在表单上
    }
  } finally {
    modalLoading.value = false;
  }
};

// 处理模态框取消
const handleModalCancel = () => {
  formRef.value?.resetFields();
  modalVisible.value = false;
};

// 打开删除确认 Modal
const openDeleteConfirmModal = (id) => {
  categoryToDeleteId.value = id;
  deleteModalVisible.value = true;
};

// 处理删除确认
const handleDeleteConfirm = async () => {
  if (categoryToDeleteId.value) {
    try {
      loading.value = true;
      const result = await cargoCategoryStore.deleteCategory(categoryToDeleteId.value);
      if (result.success) {
        Message.success('删除分类成功');
        await fetchCategoryList(); // 重新加载树
        // 如果删除的是当前选中的节点，则清空详情
        if (selectedKeys.value.length > 0 && selectedKeys.value.includes(categoryToDeleteId.value)) {
          selectedKeys.value = [];
          currentCategory.value = {};
        }
      } else {
        Message.error(result.message || '删除分类失败');
      }
    } catch (error) {
       console.error('处理删除确认时出错:', error);
       Message.error('删除分类时发生错误');
    } finally {
      loading.value = false;
      deleteModalVisible.value = false; // 关闭 modal
      categoryToDeleteId.value = null;  // 清空 id
    }
  }
};

// 获取分类详情
const fetchCategoryDetail = async (id) => {
  try {
    const result = await cargoCategoryStore.getCategoryDetail(id);
    if (result.success) {
      currentCategory.value = result.data;
      Message.success('获取分类详情成功');
    } else {
      Message.error('获取分类详情失败');
    }
  } catch (error) {
    console.error('获取分类详情失败:', error);
    Message.error('获取分类详情失败');
  }
};

// 检查层级限制
const checkLevelLimit = (parentKey) => {
  // 查找父节点的层级
  const findNodeLevel = (nodes, key, currentLevel = 1) => {
    for (const node of nodes) {
      if (node.id === key) {
        return currentLevel;
      }
      if (node.children && node.children.length > 0) {
        const level = findNodeLevel(node.children, key, currentLevel + 1);
        if (level > 0) return level;
      }
    }
    return 0;
  };
  
  const parentLevel = findNodeLevel(treeData.value, parentKey);
  
  if (parentLevel >= 3) {
    Modal.warning({
      title: '层级限制',
      content: '分类最多支持3级层级结构，不能继续添加子分类。'
    });
    return false;
  }
  
  return true;
};

// 自动生成分类编码
const generateCode = () => {
  // 使用固定前缀 'CATE'
  let baseCode = 'CATE';

  // 如果是子分类，可以考虑添加父分类编码的一部分或ID作为前缀（可选，增加区分度）
  if (form.parentId && form.parentId !== 'root') {
    const findParentCode = (nodes, key) => {
      for (const node of nodes) {
        if (node.id === key) {
          return node.code;
        }
        if (node.children && node.children.length > 0) {
          const code = findParentCode(node.children, key);
          if (code) return code;
        }
      }
      return '';
    };
    const parentCode = findParentCode(treeData.value, form.parentId);
    // 可以截取父编码一部分或直接用父ID，这里简化处理，仍用 CATE
    // if (parentCode) {
    //   baseCode = `${parentCode.substring(0, 4)}-${baseCode}`;
    // }
  }

  // 添加时间戳（取后几位）和随机后缀
  const timestampPart = Date.now().toString().slice(-5); // 取时间戳后5位
  const randomSuffix = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  
  // 确保生成的编码只包含大写字母和数字
  form.code = `${baseCode}-${timestampPart}-${randomSuffix}`.toUpperCase();
};

// 处理树形结构
const formatTreeData = (categories) => {
  if (!categories || !Array.isArray(categories)) {
    treeData.value = [];
    return;
  }

  const map = {};
  const result = [];

  // 第一遍遍历，初始化映射表和基础节点
  categories.forEach(category => {
    map[category.id] = {
      ...category,
      key: category.id,
      title: category.name,
      children: [],
      level: 0 // 初始化 level
    };
  });

  // 第二遍遍历，建立父子关系
  categories.forEach(category => {
    const node = map[category.id];
    if (category.parentId && map[category.parentId]) {
      map[category.parentId].children.push(node);
    } else {
      result.push(node); // 根节点
    }
  });

  // 第三遍遍历，计算层级并排序
  const calculateLevelAndSort = (nodes, currentLevel = 1) => {
    nodes.sort((a, b) => a.sort - b.sort);
    nodes.forEach(node => {
      node.level = currentLevel; // 设置层级
      if (node.children && node.children.length > 0) {
        calculateLevelAndSort(node.children, currentLevel + 1); // 递归计算子级
      }
    });
  };

  calculateLevelAndSort(result, 1); // 从根节点开始计算
  treeData.value = result;
};

// 格式化日期
const formatDate = () => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};
</script>

<style lang="less" scoped>
@import '@/styles/variables.less';

.container {
  padding: 0 20px 20px 20px;
}

.cards-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.general-card {
  flex: 1;
  height: calc(100vh - 120px);
  margin-top: 16px;
  
  &:first-child {
    flex: 0 0 400px;
  }
  
  :deep(.arco-card-header) {
    height: 52px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
  }
  
  :deep(.arco-card-body) {
    padding: 20px;
    height: calc(100% - 52px);
    overflow: hidden;
  }
}

.search-wrapper {
  margin-bottom: 8px;
  width: 100%;
}

.tree-container {
  height: calc(100% - 60px);
  overflow-y: auto;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  padding: 8px;
}

.detail-card {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  
  :deep(.arco-card-header) {
    background-color: #f8fafd;
  }
}

.card-title {
  display: flex;
  align-items: center;
  font-weight: 500;
  color: var(--color-text-1);
}

.detail-content {
  height: 100%;
  overflow-y: auto;
  padding: 8px;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 0;
  border-bottom: 1px solid var(--color-border-2);
  margin-bottom: 24px;
}

.category-name {
  font-size: 20px;
  font-weight: 600;
  color: var(--color-text-1);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  font-size: 14px;
  color: var(--color-text-3);
  font-weight: 500;
}

.info-value {
  font-size: 16px;
  color: var(--color-text-1);
  padding: 8px 12px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  min-height: 40px;
  display: flex;
  align-items: center;
}

.description-section {
  margin-bottom: 24px;
}

.description-content {
  margin-top: 8px;
  padding: 16px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  color: var(--color-text-1);
  min-height: 100px;
  line-height: 1.6;
}

.detail-footer {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px dashed var(--color-border-2);
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-top: 12px;
}

.related-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  font-size: 14px;
}

.empty-detail {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-fill-1);
  border-radius: 4px;
}

.tree-node-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex: 1;
  padding-right: 8px;
}

.node-actions {
  display: none;
  align-items: center;
}

:deep(.arco-tree-node:hover .node-actions) {
  display: flex;
}

:deep(.arco-tree-node-title-text) {
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.arco-tree-node) {
  padding: 4px 0;
}

:deep(.arco-tree-node-title) {
  padding: 4px 8px;
  border-radius: 4px;
}

:deep(.arco-tree-node-selected .arco-tree-node-title),
:deep(.arco-tree-node-selected:hover .arco-tree-node-title) {
  background-color: var(--color-primary-light-1) !important;
  color: rgb(var(--primary-6)) !important;
}

:deep(.arco-tree-node-title:hover) {
  background-color: var(--color-neutral-2);
}

.code-tip {
  font-size: 12px;
  color: var(--color-text-3);
  margin-top: 4px;
}
</style> 